#include "Utilities.h"

VOID GenerateRandomString(__out_ecount_z(nCount) LPWSTR lpszPath, __in int nCount)
{
  static const wchar_t cszAlphabet[] =
    L"abcdegfhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

  srand(GetTickCount());

  // extra character for NULL character
  --nCount;

  // fill buffer
  int i = 0;
  for (int len = lstrlenW(cszAlphabet); i < nCount; i++)
    lpszPath[i] = cszAlphabet[rand() % (len - 1)];
  lpszPath[i] = L'\0';
}

VOID DeleteAllInDirectory(__in_z LPCWSTR lpcszPath)
{
  LPWSTR lpszBuffer;
  HANDLE hFind;
  /***/
  WIN32_FIND_DATAW  wfd;
  SHFILEOPSTRUCTW   shfos;
    
  lpszBuffer = (LPWSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(wchar_t) * (MAX_PATH + 1));
  if (lpszBuffer != NULL)
  { 
    StringCchCopyW(lpszBuffer, MAX_PATH, lpcszPath);
    PathAppendW(lpszBuffer, L"*.*");

    hFind = FindFirstFileW(lpszBuffer, &wfd);
    if (hFind != INVALID_HANDLE_VALUE)
    {
      do {
        // are we referring to the current/above directory?
        if (lstrcmpW(wfd.cFileName, L".") == 0 || lstrcmpW(wfd.cFileName, L"..") == 0)
          continue;

        if (FAILED(StringCchCopyW(lpszBuffer, MAX_PATH, lpcszPath)))
          continue;
        if (!PathAppendW(lpszBuffer, wfd.cFileName))
          continue;

        // is it a directory?
        if (PathIsDirectoryW(lpszBuffer))
        {
          ZeroMemory(&shfos, sizeof(shfos));
          shfos.wFunc = FO_DELETE;
          shfos.pFrom = lpszBuffer;
          shfos.fFlags = FOF_NOCONFIRMATION | FOF_NO_UI;

          // must be double-NULL terminated
          MessageBoxW(NULL, lpszBuffer, 0, MB_OK);
          lpszBuffer[lstrlenW(lpszBuffer) + 1] = L'\0';

          // attempt to delete all files inside & remove directory
          if (SHFileOperationW(&shfos) == 0)
            RemoveDirectoryW(lpszBuffer);
        }
      } while (FindNextFileW(hFind, &wfd));
      FindClose(hFind);
    }
    HeapFree(GetProcessHeap(), 0, lpszBuffer);
  }
}